#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<string>
#include <sys/wait.h>
#include<sys/types.h>
int main()
{
    //创建管道
    int fds[2] = {0};
    int n = pipe(fds);
    // if(n == 0)
    // {
    //     std::cout<<"fds[0]:"<<fds[0]<<std::endl;
    //     std::cout<<"fds[1]:"<<fds[1]<<std::endl;
    // }
    if(n != 0)
    {
        std::cout<<"pipe error"<<std::endl;
        return 1;
    }
    //创建子进程
    pid_t id = fork();
    if(id < 0)
    {
        std::cout<<"fork error"<<std::endl;
        return 2;
    }
    else if(id == 0)
    {
        //关闭多余端口
        close(fds[0]);
        int cnt = 0;
        while(true)
        {
            std::string message = "hello bit，hello ";
            message += std::to_string(getpid());
            message += ", ";
            message += std::to_string(cnt);

            ::write(fds[1],message.c_str(),message.size());
            cnt++;
            sleep(1);
        }
        close(fds[1]);
        exit(0);
    }
    else
    {
        //关闭多余端口
        close(fds[1]);
        char buffer[1024];
        while(true)
        {
            size_t n = ::read(fds[0],buffer,1024);
            if(n >0)
            {
                buffer[n] = 0;
                std::cout<<"child->father,message: "<<buffer<<std::endl;
            }
        }

        close(fds[0]);
        pid_t rid = waitpid(id,nullptr,0);
        std::cout<<"father wait child success:"<<rid<<std::endl;
    }
    return 0;
}